package com.atguigu.flink.chapter07;

import com.atguigu.flink.bean.WaterSensor;
import org.apache.flink.api.common.eventtime.*;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.windowing.ProcessWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;
import com.atguigu.flink.util.AtguiguUtil;

import java.util.List;

public class Flink10_Watermark_Custom {

    public static void main(String[] args) {
        Configuration conf = new Configuration();
        conf.setInteger("rest.port", 20000);
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(conf);
        env.setParallelism(2);

        env.getConfig().setAutoWatermarkInterval(3000);

        env
                .socketTextStream("hadoop162",9999)
                .map(line -> {
                    String[] data = line.split(",");
                    return new WaterSensor(data[0], Long.valueOf(data[1]), Integer.valueOf(data[2]));
                })
                .assignTimestampsAndWatermarks(
                        WatermarkStrategy.<WaterSensor>forGenerator(new WatermarkStrategy<WaterSensor>() {
                            @Override
                            public WatermarkGenerator<WaterSensor> createWatermarkGenerator(WatermarkGeneratorSupplier.Context context) {
                                return new MyPeriodWMG();
                            }
                        })
                        .withTimestampAssigner((ws, ts) -> ws.getTs())
                )
                .keyBy(WaterSensor::getId)
                .window(TumblingEventTimeWindows.of(Time.seconds(5)))
                .process(new ProcessWindowFunction<WaterSensor, String, String, TimeWindow>() {
                    @Override
                    public void process(String key, Context ctx, Iterable<WaterSensor> elements, Collector<String> out) throws Exception {
                        List<WaterSensor> list = AtguiguUtil.toList(elements);

                        String msg = key + " " + list + " " + ctx.window();

                        out.collect(msg);

                    }
                })
                .print();

        try {
            env.execute();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static class MyPeriodWMG implements WatermarkGenerator<WaterSensor> {

        private long maxTs = Long.MIN_VALUE + 3000;

        @Override
        public void onEvent(WaterSensor event, long eventTimestamp, WatermarkOutput output) {
            System.out.println("MyPeriodWMG.onEvent");
            // 更新最大时间戳
            maxTs = Math.max(maxTs, eventTimestamp);
            output.emitWatermark(new Watermark(maxTs - 3000));
        }

        @Override
        public void onPeriodicEmit(WatermarkOutput output) {
            System.out.println("MyPeriodWMG.onPeriodicEnit");
            // 发射水印
            // output.emitWatermark(new Watermark(maxTs - 3000));
        }
    }
}
